/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.mzk.kramerius.rukopisyimport.foxml.images;

import cz.mzk.kramerius.rukopisyimport.foxml.ImageIdentifier;
import java.util.Properties;

/**
 *
 * @author Martin Rehanek (rehan@mzk.cz)
 */
public class ImageUrlBuilder {

    private static final char URL_SEPARATOR = '/';
    private static final String PROTOCOL_PREFIX = "http://";
    private static final String PROP_IMAGESERVER_URL = "ImageUrlBuilder.imageServerUrl";
    private static final String IMG_PREVIEW_SUFFIX = "/preview.jpg";
    private static final String IMG_FULL_SUFFIX = "/big.jpg";
    private static final String IMAGE_SUFFIX = ".jp2";
    private final String imageServerUrl;

    public ImageUrlBuilder(Properties properties) {
        imageServerUrl = properties.getProperty(PROP_IMAGESERVER_URL);
        if (imageServerUrl == null) {
            throw new IllegalArgumentException("Cannot load property '" + PROP_IMAGESERVER_URL + "'");
        }
    }

    public String buildTilesUrl(ImageIdentifier imageId) {
        StringBuilder result = new StringBuilder();
        result.append(PROTOCOL_PREFIX);
        result.append(imageServerUrl);
        result.append(URL_SEPARATOR);
        result.append(imageId.getBase());
        result.append(URL_SEPARATOR);
        String[] sysnoParts = sysnoToTriplets(imageId.getSysno());
        for (String sysnoPart : sysnoParts) {
            result.append(sysnoPart);
            result.append(URL_SEPARATOR);
        }
        result.append(imageId.getBarcode());
        result.append(URL_SEPARATOR);
        result.append(imageId.getPageUrlSuffix());


        return result.toString();
    }

    public String buildImgFullUrl(ImageIdentifier imgId) {
        return buildTilesUrl(imgId).concat(IMG_FULL_SUFFIX);
    }

    public String buildImgThumbUrl(ImageIdentifier imageId) {
        return buildTilesUrl(imageId).concat(IMG_PREVIEW_SUFFIX);
    }

    private String[] sysnoToTriplets(String sysno) {
        if (sysno.length() != 9) {
            throw new IllegalArgumentException("sysno '" + sysno + "' doesn't have length of 9");
        }
        String[] parts = new String[3];
        parts[0] = sysno.substring(0, 3);
        parts[1] = sysno.substring(3, 6);
        parts[2] = sysno.substring(6, 9);
        return parts;
    }
}
